<template>
  <a-modal
    :title="title"
    :width="1070"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :destroyOnClose="true"
    :centered="true"
    :footer="true"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <div class="btn">
        <a-button style="margin-right: 10px" type="primary" icon="el-icon-plus" @click="submit">保存</a-button>
        <a-button style="margin-right: 10px" type="danger" @click="clear">清空文本框</a-button>
        <a-button style="margin-right: 10px" type="" @click="addItem">追加一题</a-button>
        <a-button type="primary" @click="editTitle">题目标题编辑</a-button>
      </div>

      <a-row :gutter="20">
        <a-col :span="12">
          <textarea
            class="str_text"
            v-model="textarea"
            :style="'height:'+textHeight+'px'"
            :placeholder="placeholder"></textarea>
        </a-col>
        <a-col :span="12">
          <div class="str_list" :style="'height:'+textHeight+'px'">
            <div v-for="(x,i) in list" :key="i" style="margin-bottom: 20px">
              <div :id="'number'+(i + 1)">{{ i + 1 }}. {{ x.title }}
                <a-tag color="orange" v-if="x.qt_type==1">判断题</a-tag>
                <a-tag color="green" v-if="x.qt_type==2">单选题</a-tag>
                <a-tag color="blue" v-if="x.qt_type==3">多选题</a-tag>
              </div>
              <div
                style="border: 1px solid #ccc;font-size: 12px;padding: 10px;margin:10px 0;line-height: 20px"
                v-if="x.qt_item">
                <div
                  style="margin-bottom: 10px;padding: 0 10px"
                  v-for="(l,i2) in x.qt_item"
                  :key="i2"
                  :style="x.curr_answer.indexOf(l.item) != -1?'background: #0c69e1;color: #fff':''">
                  {{ l.item }}. {{ l.value }}
                </div>
              </div>
              <div style="font-size: 12px">
                <div v-if="x.score">分数：{{ x.score }}分</div>
                <div v-if="x.answer">答案：{{ x.answer }}</div>
                <div v-if="x.error">错误信息：
                  <span style="color:red">{{ x.error }}</span>
                  <!--                  <a-button style="margin-left: 10px" type="primary" size="small" @click="editItem(x, i)">-->
                  <!--                    修改-->
                  <!--                  </a-button>-->
                </div>
              </div>
            </div>
          </div>
        </a-col>
      </a-row>
    </a-spin>
    <EditTitleModel
      ref="EditTitleModel"
      @success="handleSuccess"
    />
  </a-modal>
</template>

<script>
import * as Api from '@/api/question/topic'
import EditTitleModel from './EditTitleModel'

export default {
  name: 'AutoModel',
  components: {
    EditTitleModel
  },
  props: ['question_id'],
  data () {
    return {
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 7
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前记录
      record: {},

      textarea: '',
      textHeight: '',
      placeholder: '请参照以下格式输入:\n\n' +
        '题目1 [判断题][2][A]\n' +
        '正确\n' +
        '错误\n' +
        '\n' +
        '题目2 [单选题][2][A]\n' +
        '选择1\n' +
        '选择2\n' +
        '选择2\n' +
        '选择2\n' +
        '\n' +
        '题目3 [多选题][2][A,B,C,D]\n' +
        '选择1\n' +
        '选择1\n' +
        '选择1\n' +
        '选择1\n' +
        '选择1\n' +
        '选择2\n',
      list: [],
      zimu: ['A', 'B', 'C', 'D', 'E'],
      topic_id: ''
    }
  },
  created () {
    this.getTextHeight()
    // this.setCookieData()
  },
  watch: {
    textarea (newValue, oldValue) {
      this.rendList()
    }
  },
  methods: {
    open () {
      this.title = '在线自动识别'
      this.visible = true
    },
    /**
     * 关闭对话框事件
     */
    handleCancel () {
      this.visible = false
      this.textarea = ''
    },

    getTextHeight () {
      this.textHeight = window.innerHeight - 199
    },
    rendList () {
      this.list = []
      if (!this.textarea) {
        return false
      }

      // 空白一行
      var v = this.textarea.split(/\n\n|\r\r|\r\n\r\n/)

      var list = []
      v.forEach((i) => {
        var arr = this.rendRow(i)
        list.push(arr)
      })
      this.list = list
      console.log(list)
    },
    rendRow (i) {
      var arr = {
        question_id: this.question_id,
        title: '',
        item: '',
        qt_item: [],
        qt_type: 1, // 1单选 2判断 3多选 默认单选
        value: '',
        score: '',
        answer: '',
        curr_answer: '',
        sort: '',
        error: []
      }
      var c = i.split(/[\r\n\r\n]+/)
      arr.title = c[0]
      var item = []
      c.slice(1).forEach((v, i) => {
        if (this.zimu[i] && v) {
          item.push({ item: this.zimu[i], value: v })
        }
      })
      arr.qt_item = item
      var qt_type = c[0].match(/(?<=\[)(.+?)(?=\])/g)
      if (qt_type && qt_type.length >= 1) {
        var qt_type_value = qt_type[0]
        if (qt_type_value == '单选题') {
          arr.qt_type = 2
          arr.sort = 1
        } else if (qt_type_value == '判断题') {
          arr.qt_type = 1
          arr.sort = 2
        } else if (qt_type_value == '多选题') {
          arr.qt_type = 3
          arr.sort = 3
        } else {
          arr.qt_type = 2
          arr.sort = 1
        }
        // arr.title = arr.title.replace('[' + qt_type_value + ']', "");
      }
      if (qt_type && qt_type.length >= 2) {
        arr.score = qt_type[1]
        // arr.title = arr.title.replace('[' + qt_type[1] + ']', "");
      }
      if (qt_type && qt_type.length >= 3) {
        arr.answer = qt_type[2]
        arr.curr_answer = qt_type[2].split(',')
        // arr.title = arr.title.replace('[' + qt_type[2] + ']', "");
      }
      if (!arr.title) {
        arr.error.push('标题不规范')
      }
      if (arr.qt_item.length <= 0) {
        arr.error.push('选项至少一项')
      }
      if (!arr.score || isNaN(arr.score) || arr.score < 0 || arr.score > 100) {
        arr.error.push('分数不规范')
      }
      var isletter2 = arr.answer
      if (!isletter2) {
        arr.error.push('答案不规范')
      }
      arr.error = arr.error.join('_')
      return arr
    },
    setData (topic_id) {
      this.topic_id = topic_id
    },
    GoScroll (number) {
      document.querySelector(number).scrollIntoView({
        behavior: 'smooth'
      })
    },
    async submit () {
      if (!this.textarea) {
        this.$message.error('请输入内容！内容不为空')
        return false
      }

      var is_ok = true
      var list = JSON.parse(JSON.stringify(this.list))
      list.forEach((v, i) => {
        if (v.error) {
          if (is_ok) {
            this.GoScroll('#number' + (i + 1))
          }
          is_ok = false
        }
      })
      if (!is_ok) {
        this.$message.error('检测到有题目不规范！请修改后重试')
        return false
      }
      list.forEach((v) => {
        var title = v.title
        var qt_type = v.qt_type == 2 ? '单选题' : v.qt_type == 1 ? '判断题' : v.qt_type == 3 ? '多选题' : ''
        title = title.replace('[' + qt_type + ']', '')
        title = title.replace('[' + v.score + ']', '')
        title = title.replace('[' + v.answer + ']', '')
        v.title = title
      })
      const { message } = await Api.autoadd({ form: list })
      this.$message.success(message)
      this.$emit('success')
      this.handleCancel()
      this.clear()
    },
    clear () {
      this.textarea = ''
    },
    addItem () {
      if (this.list.length > 0) {
        this.textarea += '\n'
      }
      this.textarea += '题目名称[单选题][2][A]\n选择1\n选择2\n选择2\n选择2\n'
    },
    editTitle () {
      this.$refs.EditTitleModel.open(this.list)
    },
    handleSuccess (content) {
      this.textarea = content
    },
    editItemSuccess (value, index) {
      this.list[index] = this.rendRow(value)
      var list = JSON.parse(JSON.stringify(this.list))
      var content = ''
      list.forEach((v, indexw) => {
        if (indexw > 0) {
          content += '\n'
        }
        var qt_type = v.qt_type == 2 ? '单选题' : v.qt_type == 1 ? '判断题' : v.qt_type == 3 ? '多选题' : ''

        v.title = v.title.replace('[' + qt_type + ']', '')
        v.title = v.title.replace('[' + v.score + ']', '')
        v.title = v.title.replace('[' + v.answer + ']', '')

        var title = v.title + '[' + qt_type + ']'
        if (v.score) {
          title += '[' + v.score + ']'
        }
        if (v.answer) {
          title += '[' + v.answer + ']'
        }

        content += title + '\n'
        v.content.forEach((c) => {
          content += c.value + '\n'
        })
      })
      this.textarea = content
    },
    editItem (x, index) {
      var content = this.rendContent(x)
      this.$refs.editItemDialog.open().setData(content, index)
      // layer.prompt({
      // 	formqt_type: 2,
      // 	title: '修改题目',
      // 	value: content
      // }, function (value, index, elem) {
      // 	var data = that.fenjie(value)
      // 	vm.list[i] = data
      // 	var list = JSON.parse(JSON.stringify(vm.list))
      // 	var content = ""
      // 	list.forEach((v, indexw) => {
      // 		if (indexw > 0) {
      // 			content += '\n'
      // 		}
      // 		var qt_type = v.qt_type == 2 ? '单选题' : v.qt_type == 1 ? '判断题' : v.qt_type == 3 ? '多选题' : ''
      //
      //
      // 		v.title = v.title.replace('[' + qt_type + ']', "");
      // 		v.title = v.title.replace('[' + v.score + ']', "");
      // 		v.title = v.title.replace('[' + v.answer + ']', "");
      //
      // 		var title = v.title + "[" + qt_type + "]"
      // 		if (v.score) {
      // 			title += "[" + v.score + "]"
      // 		}
      // 		if (v.answer) {
      // 			title += "[" + v.answer + "]"
      // 		}
      //
      // 		content += title + "\n"
      // 		v.content.forEach((c) => {
      // 			content += c.value + "\n";
      // 		})
      // 	})
      // 	vm.content = content
      // 	layer.close(index);
      // });
    },
    rendContent (str) {
      var content = ''
      var v = JSON.parse(JSON.stringify(str))
      var qt_type = v.qt_type == 2 ? '单选题' : v.qt_type == 1 ? '判断题' : v.qt_type == 3 ? '多选题' : ''
      v.title = v.title.replace('[' + qt_type + ']', '')
      v.title = v.title.replace('[' + v.score + ']', '')
      v.title = v.title.replace('[' + v.answer + ']', '')
      var title = v.title + '[' + qt_type + ']'
      if (v.score) {
        title += '[' + v.score + ']'
      }
      if (v.answer) {
        title += '[' + v.answer + ']'
      }
      content += title + '\n'
      v.content.forEach((c) => {
        content += c.value + '\n'
      })
      return content
    }
  }
}
</script>
<style scoped lang="less">
.btn {
  margin-bottom: 15px;
}

.str_text {
  width: 100%;
  border: 1px solid #e8e8e8;
  font: 14px '微软雅黑';
  resize: none;
  padding: 10px;
}

.str_list {
  width: 100%;
  border: 1px solid #e8e8e8;
  font: 14px '微软雅黑';
  padding: 10px;
  overflow-y: auto;
}
</style>
